import React, { useEffect, useRef } from "react";
import * as THREE from "three";
import { MMDAnimationHelper } from "three/examples/jsm/animation/MMDAnimationHelper.js";
import { MMDLoader } from "three/examples/jsm/loaders/MMDLoader.js";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const MMDScene = () => {
  const containerRef = useRef(null);

  useEffect(() => {
    let scene, camera, renderer, clock;
    let frameId;
    const cameraPosition = {
      x: 0,
      y: 0,
      z: 75,
    };
    const width = window.innerWidth;
    const height = window.innerHeight;

    // 初始化场景、相机、渲染器
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 2000);
    camera.position.set(cameraPosition.x, cameraPosition.y, cameraPosition.z);
    renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
    renderer.setSize(width, height);
    renderer.setClearColor(new THREE.Color(0x000000));

    // 添加灯光
    const light = new THREE.AmbientLight(0xa0a0a0);
    scene.add(light);

    // 初始化 MMDLoader 和 MMDAnimationHelper
    const loader = new MMDLoader();
    const helper = new MMDAnimationHelper();

    loader.loadWithAnimation(
      "/qque/青雀（分桦）.pmx",
      "/move/ayaka-dance.vmd",
      (mmd) => {
        helper.add(mmd.mesh, {
          animation: mmd.animation,
          physics: true,
        });
        scene.add(mmd.mesh);
      },
      undefined,
      undefined
    );

    // 初始化 OrbitControls
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.target.set(0, 10, 0);
    controls.update();

    // 添加地平面
    const planeGeometry = new THREE.PlaneGeometry(40, 40);
    const planeMaterial = new THREE.MeshBasicMaterial({ color: 0x001100 });
    const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial);
    planeMesh.rotation.x = -Math.PI / 2;
    scene.add(planeMesh);

    // 时钟
    clock = new THREE.Clock();

    // 渲染函数
    const render = () => {
      helper.update(clock.getDelta());
      renderer.render(scene, camera);
      frameId = requestAnimationFrame(render);
    };

    controls.addEventListener("change", render);

    // 挂载渲染器到 DOM
    if (containerRef.current) {
      containerRef.current.appendChild(renderer.domElement);
    }

    // 启动渲染循环
    render();

    // 组件卸载时清理资源
    return () => {
      cancelAnimationFrame(frameId);
      if (containerRef.current) {
        containerRef.current.removeChild(renderer.domElement);
      }
    };
  }, []);

  return <div ref={containerRef} id="container"></div>;
};

export default MMDScene;
